#include "uart.h"

unsigned int uart_rx_cnt=0;
unsigned char uart_rx[UART_BUF_SIZE];
unsigned char uart_rx_rp=0,uart_rx_wp=0;



void UsartInit()
{
	SCON=0X50;			//设置为工作方式1,8位uart，波特率可变
	TMOD=0X20;			//设置计数器工作方式2，8位自动重装
	PCON=0X80;			//波特率加倍
	TH1=0XF3;				//计数器初始值设置，注意波特率是4800的
	TL1=0XF3;
	ES=1;						//打开接收中断
	EA=1;						//打开总中断
	TR1=1;					//打开计数器
}

void UART1_SendData(char c){
	ES=0;
	SBUF=c;
	while(!TI);
	TI=0;
	ES=1;
}

char putchar(char c){
	UART1_SendData(c);
	return c;
}

char uart_getchar(){
	unsigned char ch;
	while(uart_rx_cnt == 0){};
		ES = 0;
		ch = uart_rx[uart_rx_rp];
		uart_rx_rp = (uart_rx_rp + 1) % UART_BUF_SIZE;
		uart_rx_cnt--;
		ES = 1;
		return ch;
}

char _getkey(){
	return uart_getchar();
}


void Usart() interrupt 4{
	ES= 0; //关串行口中断
	if(RI){
		RI= 0; //接收中断信号清零，表示将继续接收
		if(uart_rx_cnt < UART_BUF_SIZE){
			uart_rx[uart_rx_wp] = SBUF;
			uart_rx_wp = (uart_rx_wp + 1) % UART_BUF_SIZE;
			uart_rx_cnt++;
		}
	}
	ES= 1; //开串行口中断
}
